// 管理用户数据
import { defineStore } from "pinia";
import { ref } from "vue";
import { loginApi } from "@/apis/user";
import { mergeCartApi } from "@/apis/cart";
import { useCartStore } from "@/stores/cartStore";

export const useUserStore = defineStore(
    "user",
    () => {
        // state
        const userInfo = ref({});
        const cartStore = useCartStore();

        // action
        // 获取登陆数据
        const getUserInfo = async ({ account, password }) => {
            const res = await loginApi({ account, password });
            userInfo.value = res.result;

            // 登陆合并购物车
            if (cartStore.cartList.length > 0) {
                mergeCartApi(
                    cartStore.cartList.map((item) => {
                        return {
                            skuId: item.skuId,
                            selected: item.selected,
                            count: item.count,
                        };
                    })
                );
                cartStore.updateCartList();
            } else {
                cartStore.updateCartList();
            }
        };

        // 退出登陆
        const clearUserInfo = () => {
            userInfo.value = {};
            // 清空购物车
            cartStore.clearCart();
        };

        return {
            userInfo,
            getUserInfo,
            clearUserInfo,
        };
    },
    {
        persist: true,
    }
);
